<?php

declare(strict_types=1);

namespace App\Services\Users;

use App\Exception\InternalException;
use App\Exception\InvalidRequestException;
use App\Utils\Other\IdCardAuth\Chuanglan;
use App\Utils\Services\BaseServices;
use App\Model\Users\Payer as PayerModel;
use Hyperf\DbConnection\Db;
use function Hyperf\Translation\__;
use function Hyperf\Support\make;

/**
 * Class Payer
 * @author zx
 * @package App\Services\Users
 */
Class Payer extends BaseServices
{


    /**
     * 模型
     * @return string
     */
    public function model():string
    {
        return PayerModel::class;
    }

    /**
     * 身份证鉴权
     * @param array $params
     * @return mixed
     */
    public function auth(array $params)
    {
        if ($this->count('id') >= 20) {
            throw new InvalidRequestException(__('message.payer.count', ['num'=>20]));
        }

        /** @var PayerModel $model */
        $model = $this->where('id_card', $params['id_card'])->first();
        if ($model) {
            $model->fill(['is_default' => 1, 'mobile' => $model->mobile])->save();
            return $model;
        }

        return Db::transaction(function () use ($params) {
            /** @var PayerModel $model */
            $model = $this->withoutGlobalScopes()->where('id_card', $params['id_card'])->first();
            if ($model) { // 如果该身份证号码存在表中
                if ($model->name !== $params['name']) {
                    throw new InvalidRequestException(__('message.payer.auth.failed'));
                }
//                if ($this->where('id_card', $params['id_card'])->exists()) {
//                    throw new InvalidRequestException(__('message.model_found'));
//                }
                $selfModel = $this->create($params);
                if (!$selfModel->exists) {
                    throw new InternalException();
                }
            } else {
                /** @var Chuanglan $idCardAuth */
                $idCardAuth = make(Chuanglan::class);
                $idCardAuth->set($params['id_card'], $params['name'])->get();

                $selfModel = $this->create($params);
                if (!$selfModel->exists) {
                    throw new InternalException();
                }
            }

            return $selfModel;
        });
    }
}
